import socket
import base64


def base64_decode(name, ciphertext):
    ciphertext = ciphertext.encode('utf-8')
    ciphertext = base64.b64decode(ciphertext)
    result = ciphertext.decode('utf-8')
    f0 = open(name, "w+")
    f0.write(result)
    f0.close()
    return result


print("正在等待连接。。。。")
while True:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind(('127.0.0.1', 60000))
    s.listen()
    conn, address = s.accept()
    txet = conn.recv(1024)
    print(txet.decode('utf-8'))
    data0 = conn.recv(1024)
    if data0.decode('utf-8') == "对方已退出":
        print(data0.decode('utf-8'))
        s.close()
    elif data0.decode('utf-8') == "正在发送文件":
        print("正在接收文件。。。。")
        name = conn.recv(1024)
        data = conn.recv(1024)
        base64_decode(name.decode('utf-8'), data.decode('utf-8'))
        print("已接收："+name.decode('utf-8'))
        conn.sendall("发送成功".encode('utf-8'))
    else:
        print("客户端："+data0.decode('utf-8'))
        conn.sendall(("服务端已接收：" + str(data0.decode('utf-8'))).encode('utf-8'))